var API = require('API');
agGrid.initialiseAgGridWithAngular1(angular);
var app = angular.module('sales', ['ngRoute', 'agGrid','localytics.directives'])


    .controller("HomeController", require('HomeController'))
    .controller("UserController", require('UserController'))
    .controller("RoleController", require('RoleController'))
    .controller("RanksController", require('RanksController'))
    .controller("PrivilegesController", require('PrivilegesController'))
    .controller("ShopController", require('ShopController'))
    .controller("ShopSorterController", require('ShopSorterController'))
    .controller("ShopUserController", require('ShopUserController'))
    .controller("ImportController", require('ImportController'))
    .controller("ShopMapperController", require('ShopMapperController'))

    .directive('datetimepicker', require('angular-datetimepicker'))
    .directive('checkboxes', require('angular-checkboxes'))
    .directive('userPicker', require('angular-userpicker'))
    .directive('shopPicker', require('angular-shoppicker'))
    .directive('memberShopPicker', require('angular-member-shoppicker'))
    .directive('vmInput', require('angular-vehiclemodelinput'))
    .directive('salesmanPicker', require('angular-salesmanpicker'))
    .directive('evaluatorPicker', require('angular-evaluatorpicker'))
    .directive('vehicleDemoPicker', require('angular-vehicledemopicker'))
    .directive('sorter', require('angular-sorter'))
    .directive('filter', require('angular-filter'))

    //directive-forms
    .directive('userInc', require('user-inc'))
    .directive('shopInc', require('shop-inc'))


    .directive('contenteditable', require('angular-contenteditable'))

    .config(['$routeProvider', '$locationProvider',
        function ($routeProvider, $locationProvider) {
            $locationProvider.html5Mode(true);
            $routeProvider
                .when('/index.html', {
                    templateUrl: "/views/home.html",
                    controller: 'HomeController'
                })
                .when('/', {
                    templateUrl: "/views/home.html",
                    controller: 'HomeController'
                })
                .when('/users', {
                    templateUrl: "views/users.html",
                    controller: 'UserController'
                })
                .when('/shops', {
                    templateUrl: "views/shops.html",
                    controller: 'ShopController'
                })
                .when('/shop_sorter', {
                    templateUrl: "views/shop_sorter.html",
                    controller: 'ShopSorterController'
                })
                .when('/roles', {
                    templateUrl: "views/roles.html",
                    controller: 'RoleController'
                })
                .when('/shop_user', {
                    templateUrl: "views/shop_user.html",
                    controller: 'ShopUserController'
                })
                .when('/ranks', {
                    templateUrl: "views/ranks.html",
                    controller: 'RanksController'
                })
                .when('/privileges', {
                    templateUrl: "views/privileges.html",
                    controller: 'PrivilegesController'
                })


                .when('/import', {
                    templateUrl: 'views/import.html',
                    controller: 'ImportController'
                })

                // admin
                .when('/admin/users', {
                    templateUrl: '/modules/admin/users/users.html',
                    controller: require('users_ctrl')
                })
                .when('/admin/privileges', {
                    templateUrl: '/modules/admin/privileges/privileges.html',
                    controller: require('privileges_ctrl')
                })
                .when('/admin/ranks', {
                    templateUrl: '/modules/admin/ranks/ranks.html',
                    controller: require('ranks_ctrl')
                })
                .when('/admin/shops', {
                    templateUrl: '/modules/admin/shops/shops.html',
                    controller: require('shops_ctrl')
                })
                .when('/admin/shop_user', {
                    templateUrl: '/modules/admin/shop_user/shop_user.html',
                    controller: require('shop_user_ctrl')
                })

                .when('/admin/set_user', {
                    templateUrl: '/modules/admin/set_user/set_user.html',
                    controller: require('set_user_ctrl')
                })
                .when('/repair/order',{ templateUrl: '/modules/repair/order/order.html', controller: require('order_ctrl') })
                .when('/repair/shop_mapper',{ templateUrl: '/modules/repair/shop_extra/shop_mapper.html', controller:'ShopMapperController' })
.when('/performance/dailyReport',{ templateUrl: '/modules/performance/dailyReport/dailyReport.html', controller: require('dailyReport_ctrl') })
                .otherwise({
                    templateUrl: "/404.html"
                })
        }])
    .factory("loginServ", ['$q', function ($q) {

        var cache_user = void 0;
        var cache_roles = void 0;

        var t = {

            async_validate_role: function (role_id) {
                var d = $q.defer();
                t.user().then(function (user) {
                    var found = user._roles
                            .filter(function (x) {
                                return x.id == role_id
                            })
                            .length > 0;
                    d.resolve(found);
                });
                return d.promise;
            },

            validate_role: function (role_id) {
                if (cache_roles) {
                    //console.log('user', user, user._roles);
                    var found = cache_roles
                            .filter(function (x) {
                                return x.id == role_id
                            })
                            .length > 0;
                    return found;
                }
                else {
                    // console.warn("cache_roles null, need async?");
                    return false;
                }
            },

            user: function () {
                var deferred_user = $q.defer();
                if (cache_user) {
                    deferred_user.resolve(cache_user);
                } else
                    API.sys.login_user(function (user) {
                            t.roles(user.id).then(function (roles) {
                                user._roles = roles.filter(function (x) {
                                    return x.rolename.startsWith('R')
                                });
                                user._shop._brands = (user._shop.brands || "").split(",")
                                    .map(function (to_trim_quotes) {
                                        return to_trim_quotes.substring(1, to_trim_quotes.length - 1);
                                    });
                                deferred_user.resolve(cache_user = user);
                            });
                        }, function () {

                        }
                    );

                return deferred_user.promise;
            },

            roles: function (user) {

                var deferred_roles = $q.defer();
                if (cache_roles) {
                    deferred_roles.resolve(cache_roles);
                } else
                    API.rbac.roles_for_user(user, function (roles) {
                        deferred_roles.resolve(cache_roles = roles);
                    });

                return deferred_roles.promise;
            },


            menu: function () {
                //if (cache_menu) {
                //    deferred_menu.resolve(cache_menu);
                //} else
                var deferred_menu = $q.defer();
                API.sys.menu(function (menu) {
                    //cache_menu = menu;
                    deferred_menu.resolve(menu);
                });

                return deferred_menu.promise;
            }
        };
        return t;
    }])
    .run(['$rootScope', 'loginServ', '$location', '$route',
        function ($rootScope, loginServ, $location, $route) {
            // var cur_menu = 0;
            $rootScope.notifications = [];
            // var cur_menu = 0;
            var socket;
            if (!window.WebSocket) {
                window.WebSocket = window.MozWebSocket;
            }

            socket = new WebSocket("ws://" + window.location.host + "/wscnct");
            socket.onmessage = function (event) {
                if (event && event.data) {
                    var data = JSON.parse(event.data);
                    var type = data.type;

                    data.content.title = data.content.taskName.split(':')[0];
                    data.content.name = data.content.taskName.split(':')[1];
                    data.content.progress = parseInt(data.content.progress * 100);


                    // console.log('swswsw',data.content);

                    switch (type) {
                        case "normal": {
                            $rootScope.$apply(function () {
                                $rootScope.notifications.push(data);
                            });
                            break;
                        }
                        case "log": {
                            $rootScope.$apply(function () {
                                $rootScope.notifications.push(data);
                            })
                            break;
                        }
                        case "progress": {
                            console.log(data);
                            var search = $rootScope.notifications.filter(function (x) { return x.content.taskId == data.content.taskId });
                            if (search && search.length == 1) {
                                $rootScope.$apply(function () {
                                    search[0].content.progress = data.content.progress
                                })
                            } else {
                                $rootScope.$apply(function () {
                                    $rootScope.notifications.push(data);
                                })
                            }
                            //build or find progress bar
                            break;
                        }
                    }
                }
            };
            socket.onopen = function (event) {
                // console.log(event);
            };
            socket.onclose = function (event) {
                // console.log(event);
            };
            //TODO 做成service
            loginServ.user().then(function (user) {
                if (user) {
                    $rootScope.user = user;
                    // var view_shops;
                    loginServ.menu().then(function (data) {
                        //parse menus
                        $rootScope.menus = data;
                        // $rootScope.menus = data.reduce(function (accu, cur) {
                        //     if (accu[cur.module]) {
                        //         accu[cur.module].push(cur)
                        //     } else {
                        //         accu[cur.module] = [cur]
                        //     }
                        //     return accu;
                        // }, {});

                        $rootScope.module = 'insurance';


                        $rootScope.admin_rolename_show = false;

                        // Object.keys($rootScope.menus).forEach(function(i){
                        //     $rootScope.menus[i].forEach(function(m){
                        //         m.icon = false;
                        //         if (m.href == $location.url()) {
                        //             m.icon = true;
                        //         }
                        //     });
                        // });


                    });

                    $rootScope.$watch('module', function (val) {
                        if (val) {
                            $rootScope.menu = $rootScope.menus[val];
                            $rootScope.module_class = val + '-style';
                            var path = $location.path();
                            if (!$rootScope.menu) {
                                // console.warn('WARN menu null', $rootScope.menus);
                                return;
                            }
                            var result = $rootScope.menu.find(function (m) {
                                return m.href == path
                            });
                            $rootScope.title = result ? result.rolename : '';
                            // $rootScope.menu[current_menu].icon = true;
                        }
                    });

                }
            });

            /**************************************************************************************/
            $rootScope.pathname = window.location.pathname;
            //左边导航
            $rootScope.open_module = function (href,e) {

                $(e.target).addClass('active').siblings('li').removeClass('active');
                $location.path(href);

            }
            /**************************************************************************************/

            $rootScope._today = new Date();
            $rootScope.toggle_help = (sessionStorage.getItem("toggle_help") == 'true');

            $('.help-doc').css({display: $rootScope.toggle_help ? "block" : "none"});

            $rootScope.$watch('toggle_help', function (val, old) {
                // console.log('watch toggle_help', val);
                //if(val !== undefined && val != old )
                //$('.help-doc').css({display:Boolean(val)?"block":"none"});
                sessionStorage.setItem("toggle_help", val);
            });

            $rootScope.validate_role = loginServ.validate_role;

            $rootScope.me_data_submit = function () {
                API.user.upd($rootScope.user, function () {
                    alert("修改成功！");
                })
            };

        }]);

(function (app) {
    var filters = require('StaticValue');
    //console.log('LOADING sales filters');
    Object.keys(filters)
        .forEach(function (k) {
            app.filter(k, function () {
                return filters[k]
            });
        });
    //var staticFilters=require('');
})(app);
